package com.bootdo.mall_part.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.plaf.metal.MetalLabelUI;

import com.alibaba.fastjson.JSON;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.lvyou.domain.LvyouCity;
import com.bootdo.lvyou.service.LvyouCityService;
import com.bootdo.mall_part.domain.MallEvaluate;
import com.bootdo.mall_part.service.MallEvaluateService;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ModelAttribute;
import com.bootdo.common.controller.BaseController;
import com.bootdo.mall_part.domain.MallHousePlot;
import com.bootdo.mall_part.service.MallHousePlotService;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;

/**
 * 
 * 
 * @author haojiangbo
 * @email 2100272728@qq.com
 * @date 2019-11-09 10:12:48
 */
 
@Controller
@RequestMapping("/mall_part/mallHousePlot")
public class MallHousePlotController extends BaseController{


	@Autowired
	private MallHousePlotService mallHousePlotService;

	@Autowired
	private MallEvaluateService mallEvaluateService;

	@Autowired
	private LvyouCityService lvyouCityService;

	@Autowired
	private UserService userService;
	
	@ModelAttribute
	public MallHousePlot get(@RequestParam(required=false) Long id) {
		if (id != null){
			return mallHousePlotService.get(id);
		}else{
			return new MallHousePlot();
		}
	}


	
	//insert into sys_menu(parent_id,name,url,perms,type)  values (149,'测试','/mall_part/mallHousePlot','mall_part:mallHousePlot:mallHousePlot',1)
	//insert into sys_menu(parent_id,name,url,perms,type)  values (160,'修改','','mall_part:mallHousePlot:edit',2)
	//type 0是分类菜单 1是小菜但 2是按钮
	@GetMapping()
	@RequiresPermissions("mall_part:mallHousePlot:mallHousePlot")	
	String MallHousePlot(MallHousePlot mallHousePlot,HttpServletRequest request,HttpServletResponse response){
	    return "mall_part/mallHousePlot/mallHousePlot";
	}
	
	@ResponseBody
	@PostMapping("/list")
	@RequiresPermissions("mall_part:mallHousePlot:mallHousePlot")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
		String cityList = (String) params.get("cityList");
		List<Long> cityListToQuery = new ArrayList<>();
		if (cityList != null) {
			Long[] ids = JSON.parseObject(cityList, Long[].class);
			if (ids.length == 1) {

				getSonList(cityListToQuery, ids[0]);

				// cityListToQuery = lvyouCityService.getIdByParent(ids[0]);
				cityListToQuery.add(0, ids[0]);
			} else if(ids.length == 2) {
				getSonList(cityListToQuery, ids[1]);
				cityListToQuery.add(ids[1]);
			} else {

			}
		}
		params.put("cityList", cityListToQuery);
        Query query = new Query(params);
		List<MallHousePlot> mallHousePlotList = mallHousePlotService.list(query);
		int total = mallHousePlotService.count(query);
		PageUtils pageUtils = new PageUtils(mallHousePlotList, total);
		return pageUtils;
	}

	private void getSonList(List<Long> result, Long parentId) {
		List<LvyouCity> byParent = lvyouCityService.getByParent(parentId);
		if (byParent.size() > 0) {
			for (LvyouCity one: byParent) {
				result.add(one.getId().longValue());
				getSonList(result, one.getId().longValue());
			}
		}
	}
	
	@GetMapping("/add")
	@RequiresPermissions("mall_part:mallHousePlot:edit")
	String add(MallHousePlot mallHousePlot,HttpServletRequest request,HttpServletResponse response){
	    return "mall_part/mallHousePlot/mallHousePlotedit";
	}

	@PostMapping("/getById")
	@ResponseBody
	R getById(MallHousePlot mallHousePlot) {
		return R.ok().put("i",mallHousePlot);
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("mall_part:mallHousePlot:edit")
	public R save( MallHousePlot mallHousePlot){
	
		if(mallHousePlotService.save(mallHousePlot)>0){
			return R.ok().put("i", mallHousePlot);
		}
		return R.error();
	}
	
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("mall_part:mallHousePlot:edit")
	public R remove( Long id){
		if(mallHousePlotService.remove(id)>0){
		return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("mall_part:mallHousePlot:edit")
	public R remove(@RequestParam("ids[]") Long[] ids){
		mallHousePlotService.batchRemove(ids);
		return R.ok();
	}

	@PostMapping( "/saveSelfAndUser")
	@ResponseBody
	@RequiresPermissions("mall_part:mallHousePlot:edit")
	public R saveSelfAndUser(@RequestParam("xiaoquItem")String xiaoquItem,
							 @RequestParam("managerItem")String managerItem){
		MallHousePlot mallHousePlot = null;
		UserDO userDO = null;
		try {
			mallHousePlot = JSON.parseObject(xiaoquItem, MallHousePlot.class);
			userDO = JSON.parseObject(managerItem, UserDO.class);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error();
		}
		if (mallHousePlotService.saveSelfAndUser(userDO, mallHousePlot, true) == 0) {
			return R.error();
		}

		return R.ok();

	}


	@PostMapping( "/saveMerchantAndUser")
	@ResponseBody
	@RequiresPermissions("mall_part:mallHousePlot:edit")
	public R saveMerchantAndUser(@RequestParam("xiaoquItem")String xiaoquItem,
							 @RequestParam("managerItem")String managerItem){
		MallHousePlot mallHousePlot = null;
		UserDO userDO = null;
		try {
			mallHousePlot = JSON.parseObject(xiaoquItem, MallHousePlot.class);
			userDO = JSON.parseObject(managerItem, UserDO.class);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error();
		}

		mallHousePlot.setHouseFlag(2);
		if (mallHousePlotService.saveSelfAndUser(userDO, mallHousePlot, false) == 0) {
			return R.error();
		}

		return R.ok();

	}

	@PostMapping( "/checkUsername")
	@ResponseBody
	@RequiresPermissions("mall_part:mallHousePlot:edit")
	public R checkUsername(@RequestParam("userName")String userName){

		// true代表可以用
		if (!userService.checkUserName(userName)) {
			return R.error("该用户已存在");
		}
		return R.ok();
	}

	@PostMapping( "/updateManager")
	@ResponseBody
	@RequiresPermissions("mall_part:mallHousePlot:edit")
	public R updateUser(@RequestParam("userId")Long userId,
						@RequestParam("name")String name,
						@RequestParam("idcard")String idcard,
						@RequestParam("mobile")String mobile,
						@RequestParam("liveAddress")String liveAddress){

		UserDO userDO = userService.getByUserId(userId);
		if (userDO == null) {
			return R.error();
		}

		userDO.setLiveAddress(liveAddress);
		userDO.setName(name);
		userDO.setIdcard(idcard);
		userDO.setMobile(mobile);
		if (userService.updatePersonal(userDO) == 0) {
			return R.error();
		}
		userDO.setPassword(null);

		return R.ok().put("i", userDO);
	}

	@PostMapping( "/deleteManager")
	@ResponseBody
	@RequiresPermissions("mall_part:mallHousePlot:edit")
	public R deleteManager(@RequestParam("userId")Long userId){

		UserDO userDO = userService.getByUserId(userId);
		if (userDO == null) {
			return R.error();
		}

		userDO.setStatus(0);
		if (userService.updatePersonal(userDO) == 0) {
			return R.error();
		}
		userDO.setPassword(null);

		return R.ok().put("i", userDO);
	}

	@PostMapping( "/updateHousePlot")
	@ResponseBody
	@RequiresPermissions("mall_part:mallHousePlot:edit")
	public R updateHousePlot(@RequestParam("id")Long housePlotId,
						@RequestParam("name")String name,
						@RequestParam("address")String address){

		MallHousePlot mallHousePlot = mallHousePlotService.get(housePlotId);
		mallHousePlot.setAddress(address);
		mallHousePlot.setName(name);

		if (mallHousePlotService.save(mallHousePlot) == 0) {
			return R.error();
		}

		return R.ok().put("i", mallHousePlot);
	}

	@PostMapping( "/editHousePlot")
	@ResponseBody
	@RequiresPermissions("mall_part:mallHousePlot:edit")
	public R editHousePlot(@RequestParam("houseId")Long mallHousePlotId){

		MallHousePlot mallHousePlot = mallHousePlotService.get(mallHousePlotId);
		Map<String, Object> param = new HashMap<>();
		param.put("status", 1);
		if (mallHousePlot.getHouseFlag() == 1) {
			param.put("communityId", mallHousePlot.getId());
		} else if (mallHousePlot.getHouseFlag() == 2) {
			param.put("merchantId", mallHousePlot.getId());
		} else {
			return R.error();
		}

		List<UserDO> list = userService.list(param);
		for (UserDO one: list) {
			one.setPassword(null);
		}

		return R.ok().put("i", mallHousePlot).put("userList", list);
	}

	@PostMapping( "/addManager")
	@ResponseBody
	@RequiresPermissions("mall_part:mallHousePlot:edit")
	public R addManager(@RequestParam("houseId")Long mallHousePlotId,
						@RequestParam("userString")String userString,
						@RequestParam(value = "houseFlag", defaultValue = "0")Integer houseFlagInt){

		MallHousePlot mallHousePlot = mallHousePlotService.get(mallHousePlotId);
		if (mallHousePlot == null) {
			return R.error();
		}

		boolean houseFlag = true;

		UserDO userDO = JSON.parseObject(userString, UserDO.class);

//		if (houseFlagInt == 2) {
//			houseFlag = false;
//		}
		if (mallHousePlot.getHouseFlag() == 2) {
			houseFlag = false;
		}

		if (mallHousePlotService.addManager(mallHousePlot, userDO, houseFlag) == 0) {
			return R.error();
		}

		return R.ok();
	}

	@PostMapping( "/replierMember")
	@ResponseBody
	@RequiresPermissions("mall_part:mallHousePlot:replier")
	public R replierMember(@RequestParam("evaluateId")Long evaluateId,
						   @RequestParam("content")String content){

		MallEvaluate mallEvaluate = mallEvaluateService.get(evaluateId);
		if (mallEvaluate == null) {
			return R.error("参数错误");
		}

		UserDO user = ShiroUtils.getUser();

		if (mallEvaluate.getGrandFatherId() != null && mallEvaluate.getGrandFatherId() == 0) {
			mallEvaluate.setGrandFatherId(evaluateId);
		}
		mallEvaluate.setId(null);
		mallEvaluate.setReplierId(mallEvaluate.getCommentId());
		mallEvaluate.setReplierType(1);
		mallEvaluate.setReplierName(mallEvaluate.getCommentName());
		mallEvaluate.setReplierAvater(mallEvaluate.getCommentAvater());

		mallEvaluate.setCommentId(ShiroUtils.getUserId());
		mallEvaluate.setCommentName(user.getMerchantName());
		mallEvaluate.setCommentType(2);
		mallEvaluate.setIsRead(1);

		mallEvaluate.setContent(content);
		mallEvaluate.setParentId(evaluateId);



		if (mallEvaluateService.save(mallEvaluate) == 0) {
			return R.error("回复失败");
		}
		return R.ok("回复成功").put("i", mallEvaluate);
	}

}